<template>
  <div>
    <div class="filter_container">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="城市">
          <el-select v-model="deptIds" size="small" placeholder="请选择城市" multiple @visible-change='citydataList'
            @change="getdeptIdsIds" ref='deptNameRef' @keydown.native="selectBlur($event)">
            <el-option v-for="item in cityList" :key="item.id" size="small" :label="item.deptName"
              :value="{ label: item.deptName, value: item.id }">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发起日期">
          <el-date-picker v-model="Launchdate" type="daterange" range-separator="至" start-placeholder="开始日期"
            :clearable='false' end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain size="small" icon="el-icon-search" @click="handleFilter()">查询</el-button>
          <el-button type="success" plain size="small" icon="el-icon-download" @click="handleExport()"
            onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="Abnormal-list">
      <el-table :data="tableDataList" border style="width: 100%">
        <el-table-column label="后台单号" prop="xmbzNo" width="180" fixed align="center"></el-table-column>
        <el-table-column label="平台单号" prop="platformOrderId" width="180" fixed align="center"></el-table-column>
        <el-table-column label="创建人" prop="operator" width="120" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="申请原因/补差价单号" prop="reason" width="120" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="审核人" prop="personDispose" width="120" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="审核结果" prop="processingResults" width="120" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="审核状态" prop="handleStateName" width="120" align="center"></el-table-column>
        <el-table-column label="申请来源" prop="sourceName" width="120" align="center"></el-table-column>
        <el-table-column label="城市" prop="cityName" width="120" align="center"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="审核时间" prop="endTime" width="180" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="修改前" prop="beforJaon" width="180" align="center">
          <template slot-scope="{row}">
            <div v-if="row.beforePrice">总价格（<span class="c-red fw-bold">{{ Number(row.beforePrice) / 100 }}</span> 元）</div>
            <div v-if="row.beforeSkuList">
              <div v-for="(item, index) in row.beforeSkuList" :key="index">
                {{ item.name }}（{{ Number(item.originalPrice) / 100 }} 元）
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="修改后" prop="afterJson" width="180" align="center">
          <template slot-scope="{row}">
            <div v-if="row.afterPrice">总价格（<span class="c-red fw-bold">{{ Number(row.afterPrice) / 100 }}</span> 元）</div>
            <div v-if="row.afterSkuList">
              <div v-for="(item, index) in row.afterSkuList" :key="index">
                {{ item.name }}（{{ Number(item.originalPrice) / 100 }} 元）
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="差价" align="center" :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            {{ ((Number(row.afterPrice) - Number(row.beforePrice)) / 100) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

  </div>
</template>

<script>
import {
  deptdepts,
  getChannelList
} from "@/api/statistics";
import {
  getExcelShowData
} from "@/api/statistics";
import { stringToObject } from "@/util/util";
export default {
  data() {
    return {
      cityList: [], //城市
      channelList: [], //渠道
      tableDataList: [], //退款订单数据
      deptIds: [],
      channelId: [],
      channelIdslist: [],
      deptIdsIdslist: [],
      Launchdate: [
        this.dayjs(
          new Date()
        )
          .format("YYYY-MM-DD"),
        this.dayjs(
          new Date()
        )
          .format("YYYY-MM-DD"),
      ],
    }
  },
  mounted() {
    this.getOrderList();
    window.addEventListener("keydown", this.keyupEnter);
  },
  destroyed() {
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    selectBlur(e) {
      if (e.keyCode == 13) {
        this.$refs['deptNameRef'].blur();
        this.$refs.channelIdRef.blur();
        e.returnValue = false;
      }
    },
    // 回车事件
    keyupEnter() {
      if (window.event.keyCode == 13) {
        this.handleFilter(); // 查询事件
      }
    },
    citydataList() {
      deptdepts("").then(response => {
        this.cityList = response.data.data;
      });
    },
    getchannelIds(data) {
      this.channelIdslist = data;
    },
    getdeptIdsIds(data) {
      this.deptIdsIdslist = data;
    },
    getChannelList() {
      getChannelList().then(response => {
        this.channelList = response.data.data;
      })
    },
    getOrderList() {
      const errorMsg = this.validateParams()
      if (errorMsg) {
        this.$message({
          showClose: true,
          message: errorMsg,
          type: "warning"
        });
        return
      }
      const params = this.getParams()
      // 订单列表分页
      getExcelShowData(params).then(response => {
        this.tableDataList = (response.data.data || []).map(item => {
          const beforeList = item.beforJaon.split(':');
          const beforePrice = beforeList[0];
          const beforeSkuList = stringToObject(item.beforJaon.slice(beforePrice.length + 1, item.beforJaon.length));
          const afterList = item.afterJson.split(':');
          const afterPrice = afterList[0];
          const afterSkuList = stringToObject(item.afterJson.slice(afterPrice.length + 1, item.afterJson.length));
          return {
            ...item,
            beforePrice,
            beforeSkuList,
            afterPrice,
            afterSkuList,
          }
        })
      });
    },
    handleFilter() { //查询
      this.getOrderList();
    },

    handleExport() { //导出
      const errorMsg = this.validateParams()
      if (errorMsg) {
        this.$message({
          showClose: true,
          message: errorMsg,
          type: "warning"
        });
        return
      }
      const params = this.getParams()
      var user = JSON.parse(localStorage.getItem('saber-userInfo'));
      window.open(
        `/api/xmbz-statistics/orderStatistics/downLoadExcel?excelType=MODIFSKU&startTime=${params.startTime}&endTime=${params.endTime}&deptIds=${params.deptIds}&blade-auth=bearer ${user['content'].accessToken}`
      )
    },

    getParams() {
      const params = {
        excelType: 'MODIFSKU', //订单统计
        channelIds: this.channelIdslist.map(item => item.value).join(','),
        deptIds: this.deptIdsIdslist.map(item => item.value).join(','),
        startTime: this.dayjs(this.Launchdate[0]).format("YYYY-MM-DD"),
        endTime: this.dayjs(this.Launchdate[1]).format("YYYY-MM-DD"),
      }
      return params
    },

    validateParams() {
      let errorMsg = this.validateTime()
      if (errorMsg) {
        return errorMsg
      }
    },

    validateTime() {
      const time1 = this.dayjs(this.Launchdate[0]).valueOf()
      const time2 = this.dayjs(this.Launchdate[1]).valueOf()
      //讲两个时间相减，求出相隔的天数
      var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
      if (dayCount > 30) {
        return '时间间隔不可超过31天'
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.Nationalorders {
  padding-top: 20px;

  .filter_container {
    display: flex;

    .el-form-item {
      margin-bottom: 22px !important;
    }
  }
}
</style>
